package com.bjut.vendormgrsys.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class JsonUtils {

    public static final ObjectMapper mapper = new ObjectMapper();

    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    static {
        //只有不为null的字段才被序列化
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //反序列化的时候如果多了其他属性,不抛出异常
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        //序列化的时候如果是空对象的时候,不抛异常
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        //        this.objectMapper.enable(MapperFeature.AUTO_DETECT_FIELDS);
        //        this.objectMapper.disable(MapperFeature.AUTO_DETECT_GETTERS);
        //        this.objectMapper.disable(MapperFeature.AUTO_DETECT_SETTERS);
        //取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
        //        this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //        this.objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        //配置为true表示mapper接受只有一个元素的数组的反序列化
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        //可以启用的功能允许JSON空Stringvalue("")绑定为"null"，用于POJO和其他结构化值(java.util.Maps, java.util.Collections)
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        // 解析器允许在解析的内容内使用Java/C++样式注释（'/'+'*'和'//'变体）的功能。
        mapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
    }

    public static String toString(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj.getClass() == String.class) {
            return (String) obj;
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("json序列化出错：" + obj, e);
            return null;
        }
    }

    public static <T> T toBean(InputStream input, Class<T> tClass) {
        try {
            return mapper.readValue(input, tClass);
        } catch (IOException e) {
            logger.error("json解析出错：", e);
            return null;
        }
    }

    public static <T> T toBean(String json, Class<T> tClass) {
        try {
            return mapper.readValue(json, tClass);
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static <E> List<E> toList(String json, Class<E> eClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static <T> T nativeRead(String json, TypeReference<T> type) {
        try {
            return mapper.readValue(json, type);
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }
}

